/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    stack<int> st;
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,int begin,int end) {
        if(begin>end)
            return nullptr;
        int root=st.top();
        st.pop();
        TreeNode* newnode=new TreeNode(root);
        int index=0;
        for(int i=begin;i<=end;i++)
        {
            if(root==inorder[i])
                index=i;
        }

        newnode->right=_buildTree(inorder, postorder,index+1,end);
        newnode->left=_buildTree(inorder, postorder,begin,index-1);
        return newnode;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        for(auto e:postorder)
        {
            st.push(e);
        }
        return  _buildTree(inorder, postorder,0,postorder.size()-1);
    }
};